<template>
  <el-row>
    <el-form :model="model" :rules="rules" label-position="left" ref="elForm" label-width="140px">
      <!--新增 (无id: 头部表单：-->
      <Portlet title="新增账号" v-if="!id">
        <el-row :gutter="15">
          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="绑定登录手机号：" prop="phone">
              <el-input v-model="model.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="姓名：" prop="name" :rules="[
              {required: true, message: '姓名必须', trigger: 'blur'}
            ]">
              <el-input v-model="model.name"></el-input>
            </el-form-item>
          </el-col>

          <el-col :md="12" :lg="8" :xl="6" v-if="routeName === 'userAdd'">
            <el-form-item label="岗位：" prop="positionCode" :rules="[
            {required: true, message: '岗位必填', trigger: 'blur'}
          ]">
              <el-input v-model="model.positionCode" placeholder="请输入职位"></el-input>
            </el-form-item>
          </el-col>
        <!--<div class="col-xs-4" v-if="this.routeName === 'infoUserAdd'">-->
          <!--<el-form-item label="所属公司名称:" prop="companyId">-->
            <!--<el-select v-model="model.companyId" clearable placeholder="选择所属公司">-->
              <!--<el-option  v-for="item in companyArr" :key="item.value" :label="item.text" :value="item.value">-->
              <!--</el-option>-->
            <!--</el-select>-->
          <!--</el-form-item>-->
        <!--</div>-->
          <el-col :md="12" :lg="8" :xl="6" v-if="routeName === 'userAdd'">
            <el-form-item label="所属公司编号：">
              <span class="font-red">{{this.companyData.companyCode}}</span>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6" v-if="routeName === 'userAdd'">
            <el-form-item label="所属公司名称：">
              <span class="font-red">{{this.companyData.companyName}}</span>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6" v-if="routeName === 'infoUserAdd'">
            <el-form-item label="默认密码:">
             <span> 123456</span>
            </el-form-item>
          </el-col>
        </el-row>
      </Portlet>

      <!--修改(有id: 头部表单：-->
      <Portlet title="修改账号" v-if="id">
        <el-row :gutter="15">
          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="绑定登录手机号：">
             <span> {{this.companyData.phone}}</span>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6">
            <el-form-item label="姓名：" prop="name" :rules="[
                {required: true, message: '姓名必须', trigger: 'blur'}
              ]">
              <el-input v-model="model.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6" v-if="this.routeName === 'userEdit'" >
            <el-form-item label="岗位：" prop="positionCode" :rules="[
              {required: true, message: '岗位必填', trigger: 'blur'}
            ]">
              <el-input v-model="model.positionCode" placeholder="请输入职位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6" v-if="this.routeName === 'infoUserEdit'">
            <el-form-item label="默认密码:">
              <span>123456</span>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6" v-if="this.routeName === 'userEdit'">
            <el-form-item label="所属公司编号：">
              <span class="font-red">{{this.companyData.companyCode}}</span>
            </el-form-item>
          </el-col>
          <el-col :md="12" :lg="8" :xl="6" v-if="this.routeName === 'userEdit'">
            <el-form-item label="所属公司名称：">
              <span class="font-red">{{this.companyData.companyName}}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </Portlet>
      <!--下半截 角色 + 菜单 -->
      <el-row v-for="(item, index) in model.roleIds" :key="index">
        <RoleMenu :isInsert="isInsert" @delRole="delRole" @addRole="addRole" :id="id" :projectType="projectType"
                  :itemArr.sync="model.roleIds" :index="index" :item="item"></RoleMenu>
      </el-row>
      <!--按钮-->
      <el-row>
        <Portlet>
          <el-row v-if="!id">
            <el-col :span="24" class="text-center">
              <el-button class="btn-block" type="primary"
                         :loading="createLoading" @click.prevent="httpCreatePost">保 存 新 增</el-button>
            </el-col>
          </el-row>
          <el-row v-if="id">
            <template v-if="id">
              <el-col :span="24" class="text-center">
                <el-button class="btn-block" type="primary"
                           :loading="editLoading" @click.prevent="save">保 存 修 改</el-button>
              </el-col>
            </template>
          </el-row>
        </Portlet>
      </el-row>
    </el-form>
  </el-row>
</template>

<script>
import {copy, dotData} from '@/utils'
import RoleMenu from './RoleMenu'
import {isPhone} from '@/utils/validate'
// import lodash from 'lodash'
export default {
  components: {
    RoleMenu
  },
  props: {
    addRoleNum: {
      type: Number,
      default: 1
    }
  },
  created() {
    if (this.id) {
      this.getCompanyData()
      this.getDetail()
    } else {
      if (this.$route.name === 'userAdd') { // 本公司的 新增时,展示头部
        this.getCurrentCompany()
      }
      // 因getDetail初始化赋了一个空角色，so,创建的时候也赋一个空，否则后端返回角色id，请求不到菜单权限
      this.model.roleIds = [{
        roleId: ''
      }]
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      routeName: this.$route.name,
      // companyArr: [],
      editing: false,
      createLoading: false,
      editLoading: false,
      saveLoading: false,
      model: {
        userId: this.id ? this.id : '', // 若有id(即：修改),则传id
        name: '',
        roleIds: [], // 角色id权限
        phone: '',
        companyId: '',
        positionCode: '' // 职位
      },
      companyData: {}, // 请求本公司的名称和编号
      backDetail: {}, // 修改时 请求该详情
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: isPhone, message: '手机号格式有误', trigger: 'blur' }
        ]
      },
      projectType: 'storeWeb'
    }
  },
  computed: {
    // 是否是新增编辑页
    isEdit() {
      return !!this.id
    },
    isInsert() {
      // 子账号管理
      return ['userAdd', 'userEdit'].indexOf(this.routeName) >= 0 ? 1 : 0
    }
  },
  methods: {
    isPhone,
    // 请求本公司新增时的 头部信息：
    getCurrentCompany() {
      this.$ajax.get('/ms-warehouse-order/user/my-info').then(response => {
        let success = dotData(response, 'success')
        this.model.companyId = dotData(response, 'data.companyId')
        if (success) {
          this.companyData = response.data || {}
        }
      })
    },
    // 请求 本公司修改时：头部信息展示+回填
    getCompanyData() {
      this.$ajax.get('/ms-warehouse-order/user/findStorageUserById', {userId: this.id}).then(response => {
        let success = dotData(response, 'success')
        this.model.companyId = dotData(response, 'data.companyId')
        this.model.positionCode = dotData(response, 'data.position')
        this.model.name = dotData(response, 'data.name')
        if (success) {
          this.companyData = response.data || {}
        } else {
          this.errorMessage = dotData(response, 'error_message')
        }
      })
    },
    // 新增 提交
    httpCreatePost() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        let data = copy(this.model, true)
        let temp = []
        data.roleIds.forEach(v => {
          temp.push(v.roleId)
        })
        data.roleId = temp
        delete data.userId // 新增 不需要传userId
        delete data.roleIds // 删除重复的参数集合
        data.loginName = data.phone // 新增时 龚红光喊 多加一个参数
        if (this.routeName === 'infoUserAdd') {
          delete data.positionCode // 信息中心页面 不需要 岗位
        }
        if (this.routeName !== 'userAdd') { // 本公司的新增页面 才需要传公司id
          delete data.companyId
        }
        this.createLoading = true
        this.$ajax.post('/ms-warehouse-order/user/saveOrUpdateOrgUser', data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm('新增成功', '提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              if (this.routeName === 'userAdd') {
                this.$router.push({path: '/redirect/ss-oms/user/index'})
              } else {
                this.$router.push({path: '/redirect/ss-oms/info/user/index'})
              }
            })
          }
          this.createLoading = false
        }).catch(_ => {
          this.createLoading = false
        })
      })
    },
    // 修改时 请求roleId名+权限id 并 回填 下半截：
    getDetail() {
      this.$ajax.get('/ms-common-user/user/getUserAllDetails', {userId: this.id, projectType: this.projectType}).then(response => {
        this.backDetail = dotData(response, 'data')
        if (dotData(response, 'success')) {
          // 回填 this.model.orderIds
          let backOrderIds = dotData(response, 'data.roleExtBeans') || []
          if (Array.isArray(backOrderIds)) {
            this.model.roleIds = backOrderIds.map(v => {
              return {roleId: v.id}
            })
          }
        }
      }).finally(_ => { // 如果后端没有返回默认角色，就初始设置一个空角色
        if (this.model.roleIds.length === 0) {
          this.model.roleIds = [{roleId: ''}]
        }
      })
    },
    // 保存修改
    save() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        let data = copy(this.model, true)
        let temp = []
        data.roleIds.forEach(v => {
          temp.push(v.roleId)
        })
        data.roleId = temp
        delete data.companyId // 提交页面 没有说要 公司id
        delete data.phone // 不需要 提交phone
        delete data.roleIds
        data.loginName = data.phone // 修改时 龚红光也喊 多加一个参数loginName
        if (this.routeName === 'infoUserEdit') {
          delete data.positionCode // 信息中心页面 不需要 岗位
        }
        data.userId = this.id // 修改的 userId
        this.editLoading = true
        this.$ajax.post('/ms-warehouse-order/user/saveOrUpdateOrgUser', data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm('修改成功', '提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              if (this.routeName === 'userEdit') {
                this.$router.push({path: '/redirect/ss-oms/user/index'})
              } else {
                this.$router.push({path: '/redirect/ss-oms/info/user/index'})
              }
            })
          }
          this.editLoading = false
        }).catch(_ => {
          this.editLoading = false
        })
        // if (Array.isArray(data.roleId)) {
        //   let arrayData = data.roleId
        //   let tempArr = lodash.uniq(arrayData)
        //   if (arrayData.length === tempArr.length) {
        //   } else {
        //     alert('请勿重复添加相同的角色')
        //   }
        // }
      })
    },
    delRole(index) {
      this.model.roleIds.splice(index, 1)
    },
    addRole() {
      this.model.roleIds.push({
        roleId: ''
      })
    }
  }
}
</script>
